<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="企业联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入企业联系电话"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="战区" prop="supervisor">
        <el-select
          v-model="queryParams.supervisor"
          clearable
          placeholder="请选择战区"
          style="width: 200px"
          @change="handleOnChangeDept"
        >
          <el-option
            v-for="(item, index) in searchDept"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
        <!-- <el-input
          v-model="queryParams.supervisor"
          placeholder="请输入战区"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="团队" prop="department">
        <el-select
          v-model="queryParams.department"
          clearable
          placeholder="请选择团队"
          style="width: 200px"
        >
          <el-option
            v-for="(item, index) in teamList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
        <!-- <el-input
          v-model="queryParams.department"
          placeholder="请输入团队"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        /> -->
      </el-form-item>
      <el-form-item label="保护类型" prop="protectType">
        <el-select
          v-model="queryParams.protectType"
          clearable
          placeholder="请选择保护类型"
          style="width: 200px"
        >
          <el-option label="天" :value="1" />
          <el-option label="永久" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="剩余保护时长" v-if="queryParams.protectType === 1">
        <el-input-number
          v-model="queryParams.residueDayStart"
          :controls="false"
          step-strictly
          :min="0"
          style="width: 76px"
        />
        <span class="ml10 mr10">-</span>
        <el-input-number
          v-model="queryParams.residueDayEnd"
          :controls="false"
          step-strictly
          :min="0"
          style="width: 76px"
        />
        <span class="ml10">天</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="100" />
      <el-table-column
        label="企业名称"
        align="center"
        prop="companyName"
        show-overflow-tooltip
        min-width="150"
      />
      <el-table-column label="企业联系电话" align="center" prop="phone" />
      <el-table-column label="申请人" align="center" prop="applyPerson" />
      <el-table-column label="战区" align="center" prop="supervisor" />
      <el-table-column label="团队" align="center" prop="department" />
      <el-table-column
        label="剩余保护时长"
        align="center"
        :formatter="
          (row) => (row.protectType == 1 ? row.protectDay + '天' : '永久')
        "
      />
      <el-table-column
        label="操作"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="企业名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入企业名称" />
        </el-form-item>
        <el-form-item label="企业联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入企业联系电话" />
        </el-form-item>
        <el-form-item label="申请人" prop="applyPerson">
          <el-input v-model="form.applyPerson" placeholder="请输入申请人" />
        </el-form-item>
        <el-form-item label="战区" prop="supervisor">
          <el-select
            v-model="form.supervisor"
            clearable
            placeholder="请选择战区"
            style="width: 200px"
            @change="handleOnChangeDept"
          >
            <el-option
              v-for="(item, index) in searchDept"
              :key="index"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
          <!-- <el-input v-model="form.supervisor" placeholder="请输入战区" /> -->
        </el-form-item>
        <el-form-item label="团队" prop="department">
          <el-select
            v-model="form.department"
            clearable
            placeholder="请选择团队"
            style="width: 200px"
          >
            <el-option
              v-for="(item, index) in teamList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
          <!-- <el-input v-model="form.department" placeholder="请输入团队" /> -->
        </el-form-item>
        <el-form-item label="保护类型" prop="protectType">
          <el-radio-group v-model="form.protectType">
            <el-radio :label="1">天</el-radio>
            <el-radio :label="2">永久</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.protectType === 1" label="保护时长">
          <el-input-number
            v-model="form.protectDay"
            style="width: calc(100% - 30px); text-align: left"
            step-strictly
            :controls="false"
            :min="1"
            placeholder="请输入保护时长，单位天，默认7天"
          />
          <span class="ml10">天</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import * as api from '@/api/company/protect'
import { watchEffect } from 'vue'
import useUserStore from '@/store/modules/user'
import { getSearchDeptAll } from '@/api/system/config'

const { proxy } = getCurrentInstance()

const list = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: undefined,
    phone: undefined,
    supervisor: undefined,
    department: undefined,
    protectType: undefined,
    residueDayStart: undefined,
    residueDayEnd: undefined,
  },
  rules: {
    companyName: [
      { required: true, message: '企业名称不能为空', trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '企业联系电话不能为空', trigger: 'blur' },
    ],
    applyPerson: [
      { required: true, message: '申请人不能为空', trigger: 'blur' },
    ],
    supervisor: [{ required: true, message: '战区不能为空', trigger: 'blur' }],
    department: [{ required: true, message: '团队不能为空', trigger: 'blur' }],
    protectType: [
      { required: true, message: '请选择保护类型', trigger: 'blur' },
      { required: true, message: '请选择保护类型', trigger: 'change' },
    ],
  },
})

const { queryParams, form, rules } = toRefs(data)

watchEffect(() => {
  if (queryParams.value.protectType !== 1) {
    queryParams.value.residueDayStart = undefined
    queryParams.value.residueDayEnd = undefined
  }
})

getList()
getSearchDeptList()

/** 查询企业列表 */
function getList() {
  loading.value = true
  api.query(queryParams.value).then((response) => {
    list.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    companyName: undefined,
    phone: undefined,
    applyPerson: undefined,
    supervisor: undefined,
    department: undefined,
    protectType: undefined,
    protectDay: undefined,
  }
  proxy.resetForm('formRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.residueDayStart = undefined
  queryParams.value.residueDayEnd = undefined
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加企业'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  form.value = {
    ...row,
    ...{
      protectDay: Number(row.protectDay),
      protectType: Number(row.protectType),
    },
  }
  open.value = true
  title.value = '修改企业'
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      if (form.value.id !== undefined) {
        api.update(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        api.add(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id ? [row.id] : ids.value
  proxy.$modal
    .confirm('是否确认删除企业编号为"' + id + '"的数据项？')
    .then(function () {
      const idsString = id.map((item) => item.toString())
      return api.remove(idsString)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

const searchDept = ref([])
const teamList = ref([])
function handleOnChangeDept(item) {
  queryParams.value.department = ''
  teamList.value = searchDept.value.filter((o) => o.name === item)[0].list
}

function getSearchDeptList() {
  getSearchDeptAll().then((res) => {
    searchDept.value = res.data.map((o) => {
      return { name: o.parentDeptName, list: o.deptNames?.split(',') }
    })
  })
}
</script>

<style lang="less" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
